package com.sxm.yiwei;

import android.*;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;

import android.location.Location;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.app.FragmentTransaction;
import android.os.PersistableBundle;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.sxm.yiwei.activitis.AppManager;
import com.sxm.yiwei.activitis.BaseActivity;
import com.sxm.yiwei.activitis.BookContentHelpActivity;
import com.sxm.yiwei.activitis.BookContentHotActivity;
import com.sxm.yiwei.activitis.BookContentOnceActivity;
import com.sxm.yiwei.activitis.UserLoginActivity;
import com.sxm.yiwei.tools.DialogMain;
import com.sxm.yiwei.activitis.SouSuoAddNumActivity;
import com.sxm.yiwei.activitis.UserUpActivity;
import com.sxm.yiwei.activitis.CryActivity;
import com.sxm.yiwei.activitis.LocalBroadcastManager;
import com.sxm.yiwei.fragments.HomeFragment;
import com.sxm.yiwei.fragments.MessageFragment;
import com.sxm.yiwei.fragments.MineFragment;
import com.sxm.yiwei.fragments.ShopFragment;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.tools.IsLogin;
import com.sxm.yiwei.tools.MySQManager;
import com.sxm.yiwei.tools.MySqHelper;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * 程序入口
 */

public class MainActivity extends BaseActivity implements View.OnClickListener, AMapLocationListener {

    private HomeFragment homeFragment;
    public  static String a;
    private MineFragment mineFragment;
    private MessageFragment messageFragment;
    private ShopFragment shopFragment;
    private LinearLayout home;
    private LinearLayout book;
    private LinearLayout message;
    private LinearLayout mine;
    private ImageView souimg;
    private TextView bookMsg,messageMsg;
    public static boolean isForeground = true;
    private TelephonyManager telephonyManager;
    private Location location;
    private String rid;
    private String appid;
    private SharedPreferences sharedPreferences;
    private String token;
    private String userId;
    private Context context;
    private  Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 3:
                    Bundle idData = msg.getData();
                    String rid = idData.getString("rid");
                    sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
                    String mlongitude = sharedPreferences.getString("longitude", "");
                    String mlatitude = sharedPreferences.getString("latitude", "");
                    fixingregst(MainActivity.this,mlatitude,mlongitude,rid);
                    break;

                case 2:
                    Bundle data1 = msg.getData();
                    String message = data1.getString("message");
                    String extras3 = data1.getString("extras");
                    JSONObject obj3 = JSON.parseObject(extras3);
                    String aaa = obj3.getString("message");
                    Log.d(TAG, "handleMessage: 推送消息--"+aaa);
                    long l = System.currentTimeMillis();
                    SQLiteDatabase db = helper.getWritableDatabase();
                    ContentValues values = new ContentValues();
                    values.put("title",message);
                    values.put("time",String.valueOf(l));
                    values.put("message",obj3.getString("message"));
                    db.insert("yivim",null,values);
                    db.close();
                    MainActivity.this.data = msg.getData();
                    String extras = MainActivity.this.data.getString(KEY_EXTRAS);
                    JSONObject obj = JSON.parseObject(extras);
                    String type = obj.getString("type");
                    Integer ttt = Integer.valueOf(type);
                    Log.i("拼车推送",ttt+"");
                    switch (ttt){
                        case 2001:
                             DialogMain.amountDialog(AppManager.getAppManager().currentActivity(), MainActivity.this.data);
                            break;
                        case 2002:
                            DialogMain.outTimeDialog(AppManager.getAppManager().currentActivity(), MainActivity.this.data);
                            break;
                        case 2003:

                            extras1 = MainActivity.this.data.getString("extras");
                            obj1 = JSON.parseObject(extras1);
                            String longitude = obj1.getString("longitude");
                            String latitude = obj1.getString("latitude");
                            String dis = getDispatching(Double.valueOf(latitude), Double.valueOf(longitude));
                            break;
                        case 2004:
                            String extras2 = MainActivity.this.data.getString("extras");
                            JSONObject obj2 = JSON.parseObject(extras2);
                            String longitude1 = obj2.getString("longitude");
                            String latitude1 = obj2.getString("latitude");
                            String dis1 = getDispatching(Double.valueOf(latitude1), Double.valueOf(longitude1));
                            break;
                        case 2005:
                            DialogMain.cryBookMessage(AppManager.getAppManager().currentActivity(), MainActivity.this.data);
                            break;
                        case 2006:
                            DialogMain.moneyDialog(AppManager.getAppManager().currentActivity(), MainActivity.this.data);
                            break;
                        case 2007:
                            DialogMain.moneyDialog(AppManager.getAppManager().currentActivity(), MainActivity.this.data);
                            break;
                        case 2008:
                            DialogMain.cryBookMessage(AppManager.getAppManager().currentActivity(), MainActivity.this.data);
                            break;
                        case 2009:
                            DialogMain.bookAddPrice(AppManager.getAppManager().currentActivity(), MainActivity.this.data);
                            break;
                        case 2010:
                            DialogMain.SellDialog(AppManager.getAppManager().currentActivity(), MainActivity.this.data);
                            break;
                        case 2011://拼车
                            DialogMain.outMoneyDia(AppManager.getAppManager().currentActivity(), MainActivity.this.data);
                            break;
                    }
                    break;
            }
        }
    };

    private WindowManager.LayoutParams par;
    public static  String city;
    private String rid1;
    private String longitude2;
    private String latitude2;
    public static String city1;
    private String extras1;
    private JSONObject obj1;
    private Bundle data;
    private String oid;
    private double latitude;
    private double longitude;
    private double latitude1;
    private double longitude1;
    private float distance;
    private String appId;
    private MySqHelper helper;
    private String orderId1;
    private String TAG = "home";

    /*
    * E:\yivi.jks
    *keytool -v -list -keystore keystore.jks
    *keytool -v -list -keystore yivi.jks
    *
    * */

    @Override
    protected void onStart() {
        super.onStart();
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");
        rid = sharedPreferences.getString("rid", "");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showContacts();
        getLoc();
        setContentView(R.layout.activity_main);
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

        rid = JPushInterface.getRegistrationID(MainActivity.this);

        init();
        helper = MySQManager.getInstance(MainActivity.this);
        SQLiteDatabase db = helper.getWritableDatabase();
        db.close();
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");
        rid = sharedPreferences.getString("rid", "");
        registerMessageReceiver();  // used for receive msg
        initView();
        //刷新
        if (rid!=""&&appid!=""){
            toFrushUser();
        }else {}
        onFrgamentSelect(0);
        handler.postDelayed(runnable, TIME); //每隔6s执行

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);
    }

    // 设备注册和验证
    public void fixingregst(Context context, String latitude, String longitude, String rid) {
        final String registrationID = JPushInterface.getRegistrationID(this);
        final String s = JPushInterface.getRegistrationID(context);
        telephonyManager = (TelephonyManager) MainActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
        String line1Number = Build.VERSION.RELEASE;
        String pin =  Build.MODEL;
        String Imsi =  telephonyManager.getDeviceId();
        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/equipment/register");
        params.setHeader("Content-Type","application/json");
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        object.put("deviceId",Imsi);
        object.put("brand",pin);
        object.put("version",line1Number);
        object.put("registrationId",rid);
        object.put("longitude",longitude);
        object.put("latitude",latitude);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                // 获取appid
                String data = obj.getString("data");
                com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(data);
                appid = obj1.getString("appId");
                SharedPreferences sharedPreferences = getSharedPreferences("userlogin",Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString("rid", s);
                edit.putString("appid",appid);
                edit.commit();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {


            }
            @Override
            public void onCancelled(CancelledException cex) {

            }
            @Override
            public void onFinished() {
            }
        });
    }

    // 定时刷新 客户状态 10 刷一次
    private int i = 1; // 刷新次数
    private int TIME = 600000;// 10m

    // 模拟数据刷新
    Handler handler = new Handler();
    private SharedPreferences sharedPreferences1;
    private String token1;
    private String userId1;
    private String appId1;
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // handler自带方法实现定时器
            try {
                handler.postDelayed(this, TIME);
                if (rid!=""&appid!=""){
                    toFrushUser();
                }else {}

            } catch (Exception e) {

                e.printStackTrace();
            }
        }
    };
    // 定时
    private void toFrushUser() {
        sharedPreferences1 = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token1 = sharedPreferences1.getString("token", "");
        userId1 = sharedPreferences1.getString("userId", "");
        appId1 = sharedPreferences1.getString("appid", "");
        longitude2 = sharedPreferences1.getString("longitude", "");
        latitude2 = sharedPreferences1.getString("latitude", "");
        rid1 = sharedPreferences1.getString("rid", "");
        RequestParams params2 = new RequestParams(InternetAddressUtis.Url+"/equipment/directConnect");
        params2.addHeader("Content-Type","application/json");
        params2.addHeader("appId",appId1);
        params2.addHeader("token",token1);
        params2.addHeader("userId",userId1);
        JSONObject pushObj = new JSONObject();
        pushObj.put("longitude",longitude2);
        pushObj.put("latitude",longitude2);
        pushObj.put("registrationId",rid1);
        params2.setBodyContent(pushObj.toJSONString());
        Log.d("ttt", "onSuccess: 刷新---"+longitude2+"//"+latitude2);
        x.http().post(params2, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("ttt", "onSuccess: 刷新---"+result);
                i++;


            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("ttt", "onError: 刷新--"+ex);
                ErrType.errType(MainActivity.this,ex);
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });
    }

    // 获取位置信息 经纬度
    public void getLoc() {
        AMapLocationClient client = new AMapLocationClient(MainActivity.this);
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setInterval(300000);
        client.setLocationListener(this);
        client.setLocationOption(option);
        client.startLocation();
        Toast.makeText(getApplicationContext(),"定位"+client.getLastKnownLocation().getCity(),Toast.LENGTH_LONG).show();
    }
        // 测距

    private String getDispatching(Double a ,Double b) {
        sharedPreferences1 = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        longitude2 = sharedPreferences1.getString("longitude", "");
        latitude2 = sharedPreferences1.getString("latitude", "");
        RouteSearch search = new RouteSearch(MainActivity.this);
        LatLonPoint slat = new LatLonPoint(Double.valueOf(latitude2),Double.valueOf(longitude2));// 起点
        LatLonPoint elat = new LatLonPoint(a,b);// 终点
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(slat,elat);
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo,RouteSearch.DrivingShortDistance,null,null,"");
        search.calculateDriveRouteAsyn(query);
        search.setRouteSearchListener(new RouteSearch.OnRouteSearchListener() {
            @Override
            public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

            }

            @Override
            public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
                // 拿结果
                List<DrivePath> paths = driveRouteResult.getPaths();
                for (int i1 = 0; i1 < paths.size(); i1++) {
                    distance = paths.get(i1).getDistance();

                    float v = distance / 1000;
                    DecimalFormat df = new DecimalFormat("#0.00");
                    Log.d("tag", "onDriveRouteSearched: 执行了--测距");
                    DialogMain.dialogToast(AppManager.getAppManager().currentActivity(),data,df.format(v)+"");
                }
            }

            @Override
            public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

            }

            @Override
            public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

            }
        });

        return (distance/1000)+"";
    }

    private void initView(){
        home = (LinearLayout) findViewById(R.id.home);
        book = (LinearLayout) findViewById(R.id.book);
        message = (LinearLayout) findViewById(R.id.message);
        mine = (LinearLayout) findViewById(R.id.mine);
        souimg = (ImageView) findViewById(R.id.sousuo_img);
        bookMsg = (TextView) findViewById(R.id.book_msg);
        messageMsg = (TextView) findViewById(R.id.message_msg);
        // 设置消息和订单信息提示
        messageMsg.setText("10");
        // 设置加号点击事件
        souimg.setOnClickListener(this);
        souimg.setVisibility(View.VISIBLE);
        home.setSelected(true);
        book.setOnClickListener(this);
        message.setOnClickListener(this);
        mine.setOnClickListener(this);
        home.setOnClickListener(this);
    }

    private void onFrgamentSelect(int index) {
        // 开启事务
        android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
        // 隐藏fragment
        onHideFragment(ft);
        switch (index){
            case 0:
                if (homeFragment==null){
                    homeFragment = new HomeFragment();
                    ft.add(R.id.content,homeFragment);
                }else {
                    ft.show(homeFragment);
                }
                break;
            case  1:
                if (shopFragment==null){
                    shopFragment = new ShopFragment();
                    ft.add(R.id.content,shopFragment);
                }else{
                    ft.show(shopFragment);
                }
                break;
            case 2:
                if (messageFragment==null){
                    messageFragment = new MessageFragment();
                    ft.add(R.id.content,messageFragment);
                }else{
                    ft.show(messageFragment);
                }
                break;
            case 3:
                if (mineFragment==null){
                    mineFragment = new MineFragment();
                    ft.add(R.id.content,mineFragment);
                }else {
                    ft.show(mineFragment);
                }
                break;
        }

        // 提交事务
        ft.commit();
    }
    // 隐藏fragment
    private void onHideFragment(FragmentTransaction ft) {
        if (homeFragment!=null){
            ft.hide(homeFragment);
        }
        if (messageFragment!=null){
            ft.hide(messageFragment);
        }
        if (shopFragment!=null){
            ft.hide(shopFragment);
        }
        if (mineFragment!=null){
            ft.hide(mineFragment);
        }

    }
    @Override
    public void onClick(View v) {
            switch (v.getId()){
            case R.id.home:
                home.setSelected(true);
                book.setSelected(false);
                message.setSelected(false);
                mine.setSelected(false);
                onFrgamentSelect(0);
                souimg.setVisibility(View.VISIBLE);
                String s = JPushInterface.getRegistrationID(this);
                break;
            case R.id.book:
                if (token==""){

                    startActivity(new Intent(this,UserLoginActivity.class));

                }else{
                    bookMsg.setVisibility(View.INVISIBLE);
                    book.setSelected(true);
                    home.setSelected(false);
                    message.setSelected(false);
                    mine.setSelected(false);
                    onFrgamentSelect(1);
                    souimg.setVisibility(View.INVISIBLE);
                }
                /*bookMsg.setVisibility(View.INVISIBLE);
                book.setSelected(true);
                home.setSelected(false);
                message.setSelected(false);
                mine.setSelected(false);
                onFrgamentSelect(1);
                souimg.setVisibility(View.INVISIBLE);*/
                String s1 = JPushInterface.getRegistrationID(this);
                break;
            case R.id.message:
                if (token==""){

                    startActivity(new Intent(this,UserLoginActivity.class));

                }else {
                    messageMsg.setVisibility(View.INVISIBLE);
                    message.setSelected(true);
                    book.setSelected(false);
                    home.setSelected(false);
                    mine.setSelected(false);
                    onFrgamentSelect(2);
                    souimg.setVisibility(View.INVISIBLE);
                }
                break;
            case R.id.mine:
                if (token==""){
                    startActivity(new Intent(this,UserLoginActivity.class));

                }else{

                    mine.setSelected(true);
                    message.setSelected(false);
                    home.setSelected(false);
                    book.setSelected(false);
                    onFrgamentSelect(3);
                    souimg.setVisibility(View.INVISIBLE);

                }

                break;
            case R.id.img:

                startActivity(new Intent(this,CryActivity.class));

                break;
            case R.id.sousuo_img:
                if (!token.equals("")){
                    startActivity(new Intent(this,SouSuoAddNumActivity.class));
                }else {
                    startActivity(new Intent(this,UserLoginActivity.class));
                }
                break;
        }
    }

    // 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
    private void init(){
        JPushInterface.init(getApplicationContext());
    }

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
    }

    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        super.onDestroy();
    }

    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String JPUSH_ID = "jpush_id";
    public static final String ID_CONTENT = "rid";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        // 获取定位信息
        latitude = aMapLocation.getLatitude();
        longitude = aMapLocation.getLongitude();
        city = aMapLocation.getCity();
        String rid = sharedPreferences.getString("rid", "");
        if (appid==null){
            fixingregst(MainActivity.this,latitude+"",longitude+"", rid);

        }else {}
        SharedPreferences.Editor edit = sharedPreferences.edit();
        if (latitude==0.0){
            edit.putString("latitude",String.valueOf(30.500));
            edit.putString("longitude",String.valueOf(120.250));
            edit.putString("city","");
        }else {
            edit.putString("latitude",String.valueOf(latitude));
            edit.putString("longitude",String.valueOf(longitude));
            edit.putString("city",city);
        }
        edit.commit();

        Log.d("tag", "onLocationChanged: 定位--"+latitude);
    }

    public class MessageReceiver extends BroadcastReceiver {
        public Context context;
        @Override
        public void onReceive(Context con, Intent intent) {

            Bundle extras1 = intent.getExtras();
            String extra1 = extras1.getString(KEY_EXTRAS);
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {

                    Bundle extras = intent.getExtras();
                    String mm = extras.getString(KEY_MESSAGE);
                    Message m = new Message();
                    if (mm==null){
                        Bundle bb = new Bundle();
                        bb.putString("rid",intent.getStringExtra("rid"));
                        m.setData(bb);
                        m.what=3;
                        mHandler.sendMessage(m);
                    }else {
                        String extra = extras.getString(KEY_EXTRAS);

                        m.setData(intent.getExtras());
                        m.what = 2;
                        mHandler.sendMessage(m);
                    }
                }else if (JPUSH_ID.equals(intent.getAction())){
                    String rid = intent.getStringExtra("rid");


                }

            } catch (Exception e){
            }

        }
    }

    private static final int BAIDU_READ_PHONE_STATE =100;
    public void showContacts(){
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this,android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                !=PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                !=PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                !=PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                !=PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getApplicationContext(),"没有权限,请手动开启定位权限",Toast.LENGTH_SHORT).show();
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.READ_PHONE_STATE,Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, BAIDU_READ_PHONE_STATE);
        }else{
            init();
            getLoc();
        }
    }
    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    init();
                    getLoc();
                } else {
                    // 没有获取到权限，做特殊处理
                    Toast.makeText(getApplicationContext(), "获取位置权限失败，请手动开启", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }



}
